/*
 * 作者: 黄伟
 * 时间: 2017-01-19
 * 说明：
 * Copyright (c) 2016-2017 中研沃兮
 */
define(function(require) {

	require("jquery");
	var appInfo = require('app/AppInfo');
	var c = require('app/utils/CommonUtils');
	var hc = require('app/utils/HttpClientUtils');
	var tip = require('app/utils/TipUtils');
	var EchoLazyUtils = require('app/utils/EchoLazyUtils');
	var RoomInfoUtils = require('app/utils/RoomInfoUtils');
	var UserInfoUtils = require('app/utils/UserInfoUtils');
	var CacheUtils = require('app/utils/CacheUtils');
	var EventUtils=require('app/utils/EventUtils');
	var HashMap = require('app/utils/HashMapUtils');
	var APIUtils = require('app/utils/APIUtils');
	var action = {};

	var win = window;
	win.class_empty_placeholder = "empty-placeholder";

	EchoLazyUtils.load();

	//从本地数据库中获取分类：全部、自定义1、自定义2.。。
	var catalogs = RoomInfoUtils.initRoomCatalog();
	//获取“全部”类的uuid
	var all_catalog_uuid = catalogs[0].val;


	win.param = api.pageParam;

	win.refreshtime = new Date().getTime();
	win.pos = 0;
	win.roomContainer = $("#search_result-div");
	win.class_empty_placeholder = "empty-placeholder";
	win.searchResultMap = new HashMap();

	action.fetchInHeaderMode = function() {
		win.refreshtime = new Date().getTime();
		var url = appInfo.serverbase + "/wjt/catalog_rooms";
		var body = {
			keyword: win.param.keyword,
			cataloguuid: all_catalog_uuid,
			refreshtype: "head", //all, head, foot
			timestamp: win.refreshtime,
			pos: win.pos,
			size: 15
		};
		hc.post(url, body, function(resp) {
			if (resp.status != "200") {
				api.refreshHeaderLoadDone();
				return;
			}
			api.refreshHeaderLoadDone();
			var data = resp.result;
			win.pos = resp.result.pos;
			if (data.rooms.length == 0) {
				action.getNoResult();
			} else {
				win.roomContainer.html("");
				action.getResult(data);
			}

		});

	}

	action.fetchInFooterMode = function() {
		win.refreshtime = new Date().getTime();
		var url = appInfo.serverbase + "/wjt/catalog_rooms";
		var body = {
			keyword: win.param.keyword,
			cataloguuid: all_catalog_uuid,
			refreshtype: "foot", //all, head, foot
			timestamp: win.refreshtime,
			pos: win.pos,
			size: 15
		};
		hc.post(url, body, function(resp) {
			if (resp.status != "200") {
				api.refreshHeaderLoadDone();
				return;
			}
			api.refreshHeaderLoadDone();
			var data = resp.result;
			win.pos = resp.result.pos;
			if (data.rooms.length == 0) {
				api.toast({
	                msg:'下面没有了'
                });
			} else {
				action.getResult(data);
			}
		});
	}

	action.getResult = function(data) {
		var rooms = data.rooms;
		var divs = win.roomContainer;
		$("." + win.class_empty_placeholder).remove();
		rooms.forEach(function(item) {
			win.searchResultMap.put(item.uuid,item);
			//头像是否使用了缓存，如果头像地址为null，则用app中的默认图片，不使用缓存
			var avatar_use_cache = false;
			//封面是否使用了缓存，如果封面地址为null，则用app中的默认图片，不使用缓存
			var cover_use_cache = false;
			var user_avatar_url = item.thumburl;
			if (c.isNullStr(user_avatar_url)) {
				user_avatar_url = "../image/user_avatar_default.jpg";
			} else {
				user_avatar_url = c.handleUrl(user_avatar_url);
				//网络地址，缓存图片
				user_avatar_url = CacheUtils.imageCache(user_avatar_url);
				avatar_use_cache = true;
			}
			var user_avatar_div = $('<img data-echo="' + user_avatar_url + '" src="../image/user_avatar_default.jpg">');
			user_avatar_div.css({
				"border-radius": "0%",
				"width": parseInt(api.winWidth / 3) + "px",
				"height": parseInt(api.winWidth / 3) + "px"
			});

			var live_cover_url = item.livecoverurl;
			if (c.isNullStr(live_cover_url) || live_cover_url == "null") {
				live_cover_url = "../image/room_cover_default.png";
			} else {
				live_cover_url = c.handleUrl(live_cover_url);
				live_cover_url = CacheUtils.imageCache(live_cover_url);
				cover_use_cache = true;
			}

			var w = api.winWidth / 3;
			var h = api.winWidth / 3 * 9 / 16;
			var live_cover_div = $('<img data-echo="' + live_cover_url + '" src="../image/imgplaceholder.png">');
			//			 style="width:'+w+'px; height:'+h+'px">');

			var time = item.time;
			var name = item.name;
			if (item.roomchairs == null) {
				item.roomchairs = "匿名";
			}
			var room_type = item.roomType;
			var div = $(
				'<li tapmode data-avatar_use_cache="'+avatar_use_cache+'" data-cover_use_cache="'+cover_use_cache+'" data-uuid="'+item.uuid+'" data-roomuuid="'+item.uuid+'" class="aui-list-item aui-list-item-middle room-item">' +
				'<div class="aui-media-list-item-inner">' +
				'<div class="aui-list-item-media" style="width:5.75rem;">' +
				live_cover_div.prop('outerHTML') +
				'</div>' +
				'<div class="aui-list-item-inner">' +
				'<div class="aui-list-item-text">' +
				'<div class="aui-list-item-title aui-font-size-14 aui-ellipsis-2">' + name + '</div>' +
				'</div>' +
				'<div class="aui-list-item-text">' +
				RoomInfoUtils.getRoomPublicTypeTextByVal(room_type).text +
				'</div>' +
				'<div class="aui-list-item-text">' +
				c.timeFormat(item.time) +
				'</div>' +
				'</div>' +
				'</div>' +
				'</li>'
			);

			divs.append(div);
		});

		/*$(".room-item").click(function() {
			var roomuuid = $(this).data("roomuuid");
			action.enterRoom(roomuuid);
		});*/
		$(".room-item").click(function(){
			var relationData={};
			relationData.roomuuid=$(this).data("roomuuid");
			relationData.roomname=$(this).find(".aui-list-item-title").html();
			if(!c.isNull(win.param.searchtype) && win.param.searchtype=='enrollrelation'){
				api.confirm({
					title: "温馨提示",
					msg: '是否添加关联？',
		    		buttons: ['取消', '确定']
		        },function(ret,err){
		        if(ret.buttonIndex == 2){
			 		api.closeWin({
	      			});
	      			EventUtils.send('EnrollProDetailsWin','refresh_enrollRelation_list',relationData);
		        }else{
		        	api.closeWin({
        			});
		        }
		        })
				return;
			}
			var room = win.searchResultMap.get($(this).data("uuid"));
			room.avatar_use_cache =$(this).data("avatar_use_cache");
			room.cover_use_cache = $(this).data("cover_use_cache");
			c.l(room);
			if(!UserInfoUtils.isLogined()){
			//未登陆则打开LoginWin.js
				if(api.systemType == "ios"){
					if(APIUtils.doesWXloginDisplay()){
						api.openWin({
									name: 'LoginAndRegistWin',
									url: './LoginAndRegistWin.html'
						});
						return;
					}else{
						api.openWin({
										name: 'RoomWin',
										url: './RoomWin.html',
										pageParam: room
						});
					}
				}else{
					api.openWin({
								name: 'LoginAndRegistWin',
								url: './LoginAndRegistWin.html'
					});
					return;
				}
			}else{
			//进入RoomWIn页面, 并传入参数room
				api.openWin({
		            name: 'RoomWin',
		            url: './RoomWin.html',
		            pageParam: room
	            });
			}


		});
		EchoLazyUtils.load();
		api.parseTapmode();
	}
	action.getNoResult = function() {
		var div = $("<div class=\"" + win.class_empty_placeholder + "\"></div>");
		div.css({
			width: "100%",
			"font-size": "0.8rem",
			color: "#666",
			"text-align": "center"
		});
		div.html("空空如也……");
		win.roomContainer.html("");
		win.roomContainer.append(div);
	}
	action.enterRoom = function(roomuuid){
		c.l(roomuuid);
	}

	return action;
});
